package com.sunny.ihealth.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;
import com.squareup.picasso.Picasso;
import com.sunny.ihealth.BaseActivity;
import com.sunny.ihealth.R;
import com.sunny.ihealth.data.PreferencesHelper;
import com.sunny.ihealth.entity.app.SPUserInfo;
import com.sunny.ihealth.entity.bmob.UserInfo;
import com.sunny.ihealth.service.CoreService;
import com.sunny.ihealth.ui.adapter.CommonFragmentPagerAdapter;
import com.sunny.ihealth.ui.fragment.TabDateFragment;
import com.sunny.ihealth.ui.fragment.TabMeFragment;
import com.sunny.ihealth.ui.fragment.TabZoneFragment;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, ViewPager.OnPageChangeListener {

    private static final String TAG = "TAG::MainActivity";
    private static final int TAB_ME = 0;
    private static final int TAB_ZONE = 1;
    private static final int TAB_DATE = 2;

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;
    private NavigationView navigationView;
    private LinearLayout llToolbarTabs;
    private LinearLayout llDrawerHead;
    private LinearLayout llTabMe, llTabZone, llTabDate;
    private CircleImageView ivHead;
    private TextView tvNickname, tvSignature;
    private ViewPager viewPager;
    private ImageView ivTabMe, ivTabZone, ivTabDate;
    private Fragment[] fragments;
    private CommonFragmentPagerAdapter fragmentPagerAdapter;

    //按下返回键的时间
    private long pressBackTime = 0L;

    //用户信息
    private SPUserInfo spUserInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        initFragments();
        //initData();
    }

    /**
     * 初始化Fragment
     */
    private void initFragments() {
        fragments = new Fragment[3];
        fragments[0] = new TabMeFragment();
        fragments[1] = new TabZoneFragment();
        fragments[2] = new TabDateFragment();
        String[] titles = new String[]{"我的", "发现", "约跑"};
        fragmentPagerAdapter = new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments, titles);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.addOnPageChangeListener(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (getBaseApp().getUpdateState()) {
            getBaseApp().setUpdateState(false);
            initData();
            Log.i(TAG, "onResume is updating UserInfo");
        }
    }

    /**
     * 初始化账户数据，用户资料
     */
    @Override
    public void initData() {
        Log.i(TAG, "initData");
        int mode = getPreferencesHelper().getMode();
        if (mode == PreferencesHelper.MODE_REGISTER_USER) {
            spUserInfo = getPreferencesHelper().getSPUserInfo();
            if (spUserInfo == null) {
                getPreferencesHelper().setMode(PreferencesHelper.MODE_VISITOR);
                //当前用户为null
                getBaseApp().setCurrentUser(null);
                return;
            }
            llDrawerHead.setVisibility(View.VISIBLE);

            //设置当前帐户
            getBaseApp().setCurrentUser(spUserInfo.getUsername());
            //设置资料
            tvNickname.setText(spUserInfo.getNickname());
            tvSignature.setText(spUserInfo.getSignature());
            if (spUserInfo.hasHead()) {
                Picasso.with(this)
                        .load(spUserInfo.getHeadUrl())
                        .placeholder(new ColorDrawable(Color.WHITE))
                        .error(new ColorDrawable(Color.GRAY))
                        .into(ivHead);

            }

            //登陆成功，设置drawerItem
            setDrawerItems(true);


            //连接聊天
            UserInfo userInfo = BmobUser.getCurrentUser(getApplicationContext(), UserInfo.class);
            BmobIM.connect(userInfo.getUsername(), new ConnectListener() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        Log.e(TAG, "连接成功");
                    } else {
                        Log.e(TAG, "连接错误:   " + e.getMessage());
                    }
                }
            });


        } else {
            //当前用户为null
            getBaseApp().setCurrentUser(null);
        }
    }


    @Override
    public void initViews() {
        setToolbar("");

        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout_main);
        navigationView = (NavigationView) findViewById(R.id.navigation_main);
        llToolbarTabs = (LinearLayout) findViewById(R.id.ll_toolbar_tabs);
        llTabMe = (LinearLayout) findViewById(R.id.ll_toolbar_tab_me);
        llTabZone = (LinearLayout) findViewById(R.id.ll_toolbar_tab_zone);
        llTabDate = (LinearLayout) findViewById(R.id.ll_toolbar_tab_date);
        ivTabMe = (ImageView) findViewById(R.id.image_toolbar_tab_me);
        ivTabZone = (ImageView) findViewById(R.id.image_toolbar_tab_zone);
        ivTabDate = (ImageView) findViewById(R.id.image_toolbar_tab_date);
        llDrawerHead = (LinearLayout) navigationView.getHeaderView(0).findViewById(R.id.linearLayout_drawer_head);
        ivHead = (CircleImageView) llDrawerHead.findViewById(R.id.image_drawer_head);
        tvNickname = (TextView) llDrawerHead.findViewById(R.id.tv_drawer_nickname);
        tvSignature = (TextView) llDrawerHead.findViewById(R.id.tv_drawer_signature);
        viewPager = (ViewPager) findViewById(R.id.viewPager_main);


        //透明状态栏
        StatusBarUtil.setColorForDrawerLayout2(this, drawerLayout, getResources().getColor(R.color.colorPrimaryDark), getResources().getInteger(R.integer.status_alpha));

        //汉堡图标
        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, getToolbar(), R.string.drawer_open, R.string.drawer_close);
        drawerToggle.syncState();

        //显示3个在Toolbar上的按钮
        llToolbarTabs.setVisibility(View.VISIBLE);
        navigationView.setNavigationItemSelectedListener(this);

        llTabMe.setOnClickListener(this);
        llTabZone.setOnClickListener(this);
        llTabDate.setOnClickListener(this);
        llDrawerHead.setOnClickListener(this);

    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        Intent intent = null;
        Dialog dialog = null;
        switch (item.getItemId()) {
            case R.id.nav_login:
                intent = new Intent(MainActivity.this, VisitorActivity.class);
                intent.putExtra("fromMain", true);
                break;
            case R.id.nav_user:
                intent = new Intent(MainActivity.this, EditUserInfoActivity.class);
                if (spUserInfo != null) {
                    intent.putExtra("data", spUserInfo.getUserInfo());
                    intent.putExtra("fromMainUser", true);
                }
                break;
            case R.id.nav_history:
                break;
            case R.id.nav_friends:
                intent = new Intent(this, ProfileActivity.class);
                break;
            case R.id.nav_settings:
                break;
            case R.id.nav_about:
                dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("关于我们")
                        .setMessage("iHealth")
                        .setPositiveButton("确定", null)
                        .create();
                break;
            case R.id.nav_exit:
                BmobIM.getInstance().disConnect();
                stopService(new Intent(getApplicationContext(), CoreService.class));
                finish();
                return true;
        }
        drawerLayout.closeDrawer(GravityCompat.START);

        //500ms 之后启动响应功能
        if (intent != null || dialog != null) {
            final Intent finalIntent = intent;
            final Dialog finalDialog = dialog;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (finalIntent != null) {
                        startActivity(finalIntent);
                    } else {
                        finalDialog.show();
                    }
                }
            }, 500);
        }
        return false;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                    drawerLayout.closeDrawer(GravityCompat.START);
                } else {
                    drawerLayout.openDrawer(GravityCompat.START);
                }
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
                drawerLayout.closeDrawer(GravityCompat.START);
                return true;
            }
            long time = System.currentTimeMillis();
            if (time - pressBackTime > 2000) {
                pressBackTime = time;
                Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 根据登陆状态设置drawer显示什么信息
     *
     * @param isLogin
     */
    private void setDrawerItems(boolean isLogin) {
        Menu menu = navigationView.getMenu();
        MenuItem itemLogin = menu.findItem(R.id.nav_login);
        MenuItem itemInfo = menu.findItem(R.id.nav_user);
        //MenuItem itemFriend = menu.findItem(R.id.nav_friends);
        itemLogin.setVisible(!isLogin);
        itemInfo.setVisible(isLogin);
        // itemFriend.setVisible(isLogin);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_toolbar_tab_me:
                viewPager.setCurrentItem(TAB_ME, true);
                break;
            case R.id.ll_toolbar_tab_zone:
                viewPager.setCurrentItem(TAB_ZONE, true);
                break;
            case R.id.ll_toolbar_tab_date:
                viewPager.setCurrentItem(TAB_DATE, true);
                break;
            case R.id.linearLayout_drawer_head:
                Intent intent = new Intent(this, ProfileActivity.class);
                intent.putExtra("data", BmobUser.getCurrentUser(this, UserInfo.class));
                startActivity(intent);
                break;
        }
    }


    /**
     * 切换到指定的Tab
     *
     * @param whichTab tab id
     */
    private void changeTabIcon(int whichTab) {
        switch (whichTab) {
            case TAB_ME:
                ivTabMe.setAlpha(1.0F);
                ivTabZone.setAlpha(0.5F);
                ivTabDate.setAlpha(0.5F);
                break;
            case TAB_ZONE:
                ivTabMe.setAlpha(0.5F);
                ivTabZone.setAlpha(1.0F);
                ivTabDate.setAlpha(0.5F);
                break;
            case TAB_DATE:
                ivTabMe.setAlpha(0.5F);
                ivTabZone.setAlpha(0.5F);
                ivTabDate.setAlpha(1.0F);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        changeTabIcon(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
